/*******************************************************************************
 * ShowItemAction.java
 *
 * Created by jigar
 * Last modified Date: Oct 15, 2008 10:39:18 AM by nishan
  * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ******************************************************************************/
package com.printeverywhere.action;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.printeverywhere.delegator.AuctionBidsServiceDelegator;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.ItemsServiceDelegator;
import com.printeverywhere.delegator.MailServerDelegator;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.AuctionWonlist;
import com.printeverywhere.dto.ItemAuctionImage;
import com.printeverywhere.dto.AuctionBids;
import com.printeverywhere.dto.BidStatus;
import com.printeverywhere.dto.ItemOffers;
import com.printeverywhere.dto.Items;
import com.printeverywhere.dto.MailServer;
import com.printeverywhere.dto.MailingSystem;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.DateUtil;
import com.printeverywhere.util.MailHelper;
import com.printeverywhere.util.SearchCriteria;
import com.printeverywhere.util.SessionUtil;


public class AskSellerAction extends FrontBaseSupport implements ServletRequestAware {

	/**  */
	private static final long serialVersionUID = 1L;

	private HttpServletRequest request;

	private static final Logger logger = Logger.getLogger(AskSellerAction.class);

	private List<Integer> itemId = new ArrayList<Integer>();

	private List<Items> compareItemList = new ArrayList<Items>();

	private AuctionBids auctionBids;

	private Integer askSellerId = 0;

	private Items item;

	private List<ItemAuctionImage> itemAuctionImages;

	private Boolean selfCopy;

	private String questions;

	private String fromPage;

	private char[] views = new char[] {'0', '0', '0', '0', '0', '0'};

	private final boolean showItem = true;

	private MailServer mailContent = new MailServer();

	private User user;

	private ItemOffers itemOffers;

	private SearchCriteria searchCriteria = new SearchCriteria();
	
	private Integer passUserId = 0;
	
	private AuctionWonlist auctionWonlist;

	/** The file. */
	private File file;

	/** The content type. */
	private String contentType;

    /** The filename. */
    private String filename;

    private Date date;

	public File getUpload() {
		return file;
	}

	public void setUpload(File file) {
		this.file = file;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public boolean isShowItem() {
		return showItem;
	}

	public AskSellerAction() {
		super(true, false);
	}

	public String execute() throws Exception {
		user = SessionUtil.getUser(request);
		if(request.getParameter("pass") != null){
			passUserId = Integer.parseInt(request.getParameter("pass"));
			searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute("id", passUserId);
			List<AuctionWonlist> list = (List<AuctionWonlist>) CommonFunctionDelegator.GeneralgetCriteriaList(AuctionWonlist.class.getName(), searchCriteria);
			auctionWonlist = list.size() > 0 ? list.get(0) : null;
		}
		date = DateUtil.getTodaysDate();
		if(request.getParameter("cid") != null) {
			askSellerId = Integer.parseInt(request.getParameter("cid"));
			item = ItemsServiceDelegator.getItemsById(askSellerId);
			if(item.getEndTime().before(DateUtil.getTodaysDate())){
				item.setClosed(true);
			}else{
				item.setClosed(false);
			}
		}
		return SUCCESS;
	}

	public String askQuestionToSeller() throws Exception{
		User toUser; 
		askSellerId = Integer.parseInt(request.getParameter("item.itemId"));
		item = ItemsServiceDelegator.getItemsById(askSellerId);
		String subject = "Question for seller, Item Nr." + item.getItemId();
		if(request.getParameter("uid") != null){
			toUser = UserServiceDelegator.getUser(Integer.parseInt(request.getParameter("uid")));
		}else{
			toUser = item.getUserId();
		}
		
		
		if(questions != null){
			if(selfCopy == true){
				try{
					user = SessionUtil.getUser(request);
					this.mailContent.setUserByUserId(user);
					this.mailContent.setUserByFromId(user);
					this.mailContent.setBody(questions);
					this.mailContent.setSubject(subject);
					this.mailContent.setFlag(false);
					this.mailContent.setIsRead(false);
					DateFormat myDate = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");
					Calendar cal = GregorianCalendar.getInstance();
					cal.add(Calendar.MONDAY, 2);
					String strDate = myDate.format(cal.getTime());
					Date expiresDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").parse(strDate);
					this.mailContent.setExpiresDate(expiresDateFormat);
					MailingSystem mailingSystem = (MailingSystem) ActionContext.getContext().getApplication().get(AdminConstants.MAILING_OPTIONS);
					MailHelper mailHelper = new MailHelper(mailingSystem.getServerAddress(), mailingSystem.getServerUsername(), mailingSystem.getServerPassword());
					mailHelper.sendMail(mailingSystem.getWebmasterEmailAddress(), user.getEmail(), subject , questions);
					MailServerDelegator.insertMail(mailContent);
				}catch (Exception e) {
					e.printStackTrace();
					addActionError("Error when sending self copy mail");
					return execute();
				}
			}
				try{
					user = SessionUtil.getUser(request);
					this.mailContent.setUserByUserId(item.getUserId());
					this.mailContent.setUserByFromId(user);
					this.mailContent.setBody(questions);
					this.mailContent.setSubject(subject);
					this.mailContent.setFlag(false);
					this.mailContent.setIsRead(false);
					DateFormat myDate = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");
					Calendar cal = GregorianCalendar.getInstance();
					cal.add(Calendar.MONDAY, 2);
					String strDate = myDate.format(cal.getTime());
					Date expiresDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").parse(strDate);
					this.mailContent.setExpiresDate(expiresDateFormat);
					MailingSystem mailingSystem = (MailingSystem) ActionContext.getContext().getApplication().get(AdminConstants.MAILING_OPTIONS);
					MailHelper mailHelper = new MailHelper(mailingSystem.getServerAddress(), mailingSystem.getServerUsername(), mailingSystem.getServerPassword());
					mailHelper.sendMail(mailingSystem.getWebmasterEmailAddress(), toUser.getEmail() , subject , questions);
					MailServerDelegator.insertMail(mailContent);
				}catch (Exception e) {
					e.printStackTrace();
					addActionError("Error when sending mail to seller");
					return execute();
				}
		}else{
			addActionError("Please insert your question");
			return execute();
		}

		return SUCCESS;
	}

	public String showItem() {
		if(request.getParameter("cid") != null) {
			this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));
			SearchCriteria searchCriteria = new SearchCriteria();
			searchCriteria.setAttribute("id.items", this.item);
			itemAuctionImages = (List<ItemAuctionImage>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, ItemAuctionImage.class);
			int totalViews = this.item.getViews();
			this.item.setViews(totalViews + 1);
			CommonFunctionDelegator.generalUpdatebyobj(this.item);
			char[] tmpViews = String.valueOf(totalViews).toCharArray();

			for (int index = 0; index < tmpViews.length; index++) {
				this.views[tmpViews.length - index - 1] = tmpViews[index];
			}
		}
		if(request.getParameter("p") != null){
			fromPage = request.getParameter("p");
		}
		return SUCCESS;
	}

	public String confirmAuctionBid(){
		setLeftAllowed(false);
		setRightAllowed(false);
		try{
			user = SessionUtil.getUser(request);
			if(request.getParameter("cid") != null) {
				this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));
			}
			if(auctionBids.getMaxBid() < item.getCurrentBid()){
				addActionError("Your maximum bid per item can not be less than Current bid.");
				return INPUT;
			}
		}catch (Exception e) {
			user = SessionUtil.getUser(request);
			return INPUT;
		}
		return SUCCESS;
	}
	@Override
	public void validate() {
		user = SessionUtil.getUser(request);
		if(request.getParameter("cid") != null) {
			this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));
		}
	}
	@SuppressWarnings("unchecked")
	public String addAuctionBid(){
		setLeftAllowed(false);
		setRightAllowed(false);
		try{
			BidStatus bidStatus;
			user = SessionUtil.getUser(request);
			searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute(AdminConstants.ID, 4.0);
			bidStatus = (BidStatus) (CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, BidStatus.class).size() > 0 ?CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, BidStatus.class).get(AdminConstants.ZERO_NUMBER) : new BidStatus());
			if(request.getParameter("cid") != null) {
 				this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));
			}
			System.out.println(auctionBids.getMaxBid().longValue());
			item.setStartBid(auctionBids.getMaxBid());
			CommonFunctionDelegator.generalUpdatebyobj(this.item);
			ActionContext.getContext().getApplication().put(AttributeConstants.ITEMS, this.item);
			auctionBids.setBidStatus(bidStatus);
			auctionBids.setEmail(user.getEmail());
			auctionBids.setItems(item);
			auctionBids.setTime(DateUtil.getTodaysDate().toString());
			auctionBids.setUser(user);
			AuctionBidsServiceDelegator.add(auctionBids);
		}catch (Exception e) {
			return INPUT;
		}
		return SUCCESS;
	}
	public String compareItems() {
		itemId.add(1);
		itemId.add(3);

		for (int i=0;i<itemId.size();i++) {
			Items items = ItemsServiceDelegator.getItemsById(itemId.get(i));
			compareItemList.add(items);
		}
		return SUCCESS;
	}

	public String makeOffer() throws Exception{
		user = SessionUtil.getUser(request);
		if(request.getParameter("fromPage") != null){
			fromPage = request.getParameter("fromPage");
		}
		if(this.file!=null) {
			try{
			if(!CommonUtil.isImage(FileUtils.readFileToByteArray(file))){
				addActionError(getText("struts.messages.error.uploading"));
				return ERROR;
			}
			}catch (Exception e) {
				addActionError(getText("struts.messages.error.uploading"));
				return ERROR;
			}

			this.itemOffers.setImage(FileUtils.readFileToByteArray(file));
		}

		if(request.getParameter("cid") != null) {
			this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));
		}

		this.itemOffers.setItems(item);
		this.itemOffers.setUser(user);
		CommonFunctionDelegator.generalInsertbyobj(this.itemOffers);

		return SUCCESS;
	}

	/**
	 * @return the itemId
	 */
	public List<Integer> getItemId() {
		return itemId;
	}

	/**
	 * @param itemId the itemId to set
	 */
	public void setItemId(List<Integer> itemId) {
		this.itemId = itemId;
	}

	/**
	 * @return the compareItemList
	 */
	public List<Items> getCompareItemList() {
		return compareItemList;
	}

	/**
	 * @param compareItemList the compareItemList to set
	 */
	public void setCompareItemList(List<Items> compareItemList) {
		this.compareItemList = compareItemList;
	}

	public Items getItem() {
		return item;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public char[] getViews() {
		return views;
	}

	public Integer getAskSellerId() {
		return askSellerId;
	}

	public void setAskSellerId(Integer askSellerId) {
		this.askSellerId = askSellerId;
	}

	public void setItem(Items item) {
		this.item = item;
	}

	public Boolean getSelfCopy() {
		return selfCopy;
	}

	public void setSelfCopy(Boolean selfCopy) {
		this.selfCopy = selfCopy;
	}

	public String getQuestions() {
		return questions;
	}

	public void setQuestions(String questions) {
		this.questions = questions;
	}

	public MailServer getMailContent() {
		return mailContent;
	}

	public void setMailContent(MailServer mailContent) {
		this.mailContent = mailContent;
	}

	public List<ItemAuctionImage> getItemAuctionImages() {
		return itemAuctionImages;
	}

	public AuctionBids getAuctionBids() {
		return auctionBids;
	}

	public void setAuctionBids(AuctionBids auctionBids) {
		this.auctionBids = auctionBids;
	}

	public String getFromPage() {
		return fromPage;
	}

	public void setFromPage(String fromPage) {
		this.fromPage = fromPage;
	}

	public ItemOffers getItemOffers() {
		return itemOffers;
	}

	public void setItemOffers(ItemOffers itemOffers) {
		this.itemOffers = itemOffers;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	/**
	 * Sets the upload content type.
	 *
	 * @param contentType the new upload content type
	 */
	public void setUploadContentType(String contentType) {
        this.contentType = contentType;
     }

	/**
	 * Sets the upload file name.
	 *
	 * @param filename the new upload file name
	 */
	public void setUploadFileName(String filename) {
        this.filename = filename;
     }

	public String  getUploadContentType() {
	       return contentType;
	}

	public String getUploadFilename() {
		return filename;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public Integer getPassUserId() {
		return passUserId;
	}

	public void setPassUserId(Integer passUserId) {
		this.passUserId = passUserId;
	}

	public AuctionWonlist getAuctionWonlist() {
		return auctionWonlist;
	}

	public void setAuctionWonlist(AuctionWonlist auctionWonlist) {
		this.auctionWonlist = auctionWonlist;
	}

}
